<template>
  <div style="flex: 1;">
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-form-item>
        <el-table :data="httpReq" border style="width: 100%">
          <el-table-column label="序号" width="60" align="center">
            <template #default="{ $index }">
              {{ $index + 1 }}
            </template>
          </el-table-column>

          <el-table-column label="参数名称" prop="paramName">
            <template #default="{ row }">
              <el-input v-model="row.paramName" placeholder="请输入参数名称" />
            </template>
          </el-table-column>

          <el-table-column label="参数类型" prop="paramType">
            <template #default="{ row }">
              <el-select
                v-model="row.paramType"
                placeholder="请选择参数类型"
                @change="subScriptForm()"
                style="width: 100%"
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>

          <!-- <el-table-column label="参数描述" prop="paramDes">
            <template #default="{ row }">
              <el-input
                v-model="row.paramDes"
                type="textarea"
                :rows="1"
                placeholder="请输入参数描述"
              />
            </template>
          </el-table-column> -->

          <el-table-column label="输入值" prop="paramValue" width="300">
            <template #default="{ row }">
              <inputUpload
                :taskId="newScriptId"
                v-model:paramValue="row.paramValue"
                v-if="row.paramType == 'file'"
              ></inputUpload>
              <el-input
                v-else
                v-model="row.paramValue"
                placeholder="请输入值"
              />
            </template>
          </el-table-column>

          <el-table-column label="操作" width="100" align="center">
            <template #default="{ $index, row }">
              <el-button
                type="primary"
                v-if="row.paramType == 'file'"
                size="small"
                @click="settingRow(row)"
                :icon="Setting"
                circle
              />
              <el-button
                type="danger"
                size="small"
                @click="deleteRow(httpReq, $index)"
                :icon="Delete"
                circle
              />
            </template>
          </el-table-column>
        </el-table>
        <el-button style="width: 100%" @click="addNewRow(httpReq)" class="mt-4">
          <el-icon><plus /></el-icon>添加行
        </el-button>
      </el-form-item>
    </el-form>
  </div>

  <BaseDialog
    v-model="showTxtDialog"
    title="表单弹窗"
    :before-close="handleBeforeClose"
    @confirm="submitTxt"
  >
    <txtEdit v-if="showTxtDialog" ref="txtEditValue" :txtDoc="txtDoc"></txtEdit>
  </BaseDialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, onUpdated } from "vue";
import { useRouter, useRoute } from "vue-router";
import { gmtScriptinfosave, gmtScriptinfo } from "@/api/gmtScript";
import type { UploadInstance } from "element-plus";
import inputUpload from "./inputUpload.vue";
import { Plus, Delete, Setting } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import txtEdit from "./txtEdit.vue";

// saveDynamicForm 定义
interface saveDynamicForm {
  resId?: string;
  httpUrl?: string;
  httpMethod?: string;
  httpReq?: string | string[];
}

// scriptForm 定义
interface scriptForm {
  scriptName?: string;
  scriptDes?: string;
  scriptContent?: string;
}

// Props 定义
interface Props {
  modelValue?: any;
  newScriptId: any;
  disabled?: boolean;
  id?: string;
  plugins?: string | string[];
  toolbar?: string | string[];
  data?: any;
  scriptForm?: scriptForm;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: [
    {
      paramName: "",
      paramType: "",
      paramDes: "",
      paramValue: "",
    },
  ],
  newScriptId: "",
  disabled: false,
  id: "111",
  plugins: "advlist autolink lists link image table wordcount",
  toolbar:
    "undo redo | formatselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media table | removeformat",
  data: {},
});

const router = useRouter();
const route = useRoute();
//txt编辑弹窗
const showTxtDialog = ref(false);
const txtEditValue = ref();
const txtDoc = ref();

const newScriptId = ref(route.params.id);
const editorId = ref(props.id);
const formRef = ref(null);
const fristFillIn = ref(true);
const form: saveDynamicForm = reactive({});

const rules = reactive({
  httpUrl: [{ required: true, message: "请输入资源地址", trigger: "blur" }],
});

// 参数类型选项
const typeOptions = [
  { value: "1101", label: "字符串" },
  { value: "1102", label: "日期" },
  { value: "1103", label: "数字" },
  { value: "file", label: "文件" },
];

const methodOptions = [
  { value: "POST", label: "POST" },
  { value: "GET", label: "GET" },
];
onUpdated(() => {
  console.log("props.modelValue", props.modelValue);

  if (props.modelValue) {
    httpReq.value = props.modelValue;
  }
});
// 资源请求参数（Json）
const httpReq = ref(props.modelValue);
// Emits 定义
const emit = defineEmits<{
  (e: "update:modelValue", value: any): void;
  (e: "update:newScriptId", value: any): void;
}>();

// 如果是编辑，加载用户数据
onMounted(() => {});

const uploadRef = ref<UploadInstance>();

const submitUpload = () => {
  uploadRef.value!.submit();
};

//表单提交
const subScriptForm = async () => {
  if (route.params.id == "add" && fristFillIn.value) {
    const data: any = await gmtScriptinfosave({
      scriptName: props.scriptForm.scriptName,
      scriptDes: props.scriptForm.scriptDes,
      scriptContent: props.scriptForm.scriptContent,
    });
    newScriptId.value = data;
    fristFillIn.value = false;
  }
};

const settingRow = async (row) => {
  txtDoc.value = row;
  txtDoc.value.newScriptId = newScriptId.value;
  showTxtDialog.value = true;
};

// 添加新行
const addNewRow = (tableData) => {
  tableData.push({
    paramName: "",
    paramType: "",
    paramDes: "",
    paramValue: "",
  });
};

// 删除行
const deleteRow = (tableData, index) => {
  // if (tableData.length > 1) {
  tableData.splice(index, 1);
  // } else {
  //   ElMessage.warning("至少保留一行数据");
  // }
};

//是否是新增
const isNatAdd = async () => {
  if (route.params.id == "add") {
    if (Object.keys(props.data).length === 0) {
      ElMessage.error("请先填写资源类型信息");
    } else {
      const data: any = await gmtScriptinfosave(props.data);
      editorId.value = data;
    }
  }
};

//取消txt编辑
const handleBeforeClose = () => {};

const submitTxt = async () => {
  // try {
  await txtEditValue.value.saveText();
  // } catch (error) {
  //   console.error("保存文本失败:", error);
  // } finally {
  showTxtDialog.value = false;
  // }
};

const handleSave = async (content: string) => {
  // 这里调用API将内容保存到后端
  console.log("保存内容:", content);
  // 模拟API调用
  return new Promise<void>((resolve) => {
    setTimeout(() => {
      console.log("保存成功");
      resolve();
    }, 1000);
  });
};

const onSaveSuccess = async (content: string) => {
  console.log("保存成功回调:", content);
};

const onCancel = () => {
  console.log("用户取消了编辑");
};

const onContentChange = (content: string, hasChanges: boolean) => {
  console.log("内容变化:", content, hasChanges);
};

// 保存数据
const saveData = async () => {
  emit("update:modelValue", httpReq.value);
  emit("update:newScriptId", newScriptId.value);
};

defineExpose({
  saveData,
  isNatAdd,
});
</script>

<style scoped>
.user-edit-container {
  padding: 20px;
}

/* .editable-table-container {
  padding: 20px;
} */

.add-btn {
  margin-bottom: 15px;
}

.footer {
  margin-top: 15px;
  text-align: right;
}

.el-input,
.el-textarea {
  width: 100%;
}

:deep(.el-textarea__inner) {
  resize: vertical;
  min-height: 32px;
}
</style>
